<template>
  <div class="manage">
    <!-- Main Wrapper -->
    <div class="main-wrapper">
      <Header/>
      <SideBar/>
      <!-- Page Wrapper -->
      <div class="page-wrapper"><!-- :is="currentView" -->
        <div class="content container-fluid">
          <BreadCrumb/>

          <h2>师生账户管理</h2>
            身份：<el-select v-model="user_type" placeholder="请选择身份">
						<el-option
						v-for="item in type_options"
						:key="item.value"
						:label="item.label"
						:value="item.value">
						</el-option>
					</el-select>
            姓名：<el-input v-model="user_name" placeholder="请输入局部姓名" class="account"></el-input>
            身份证号：<el-input v-model="id_card" placeholder="请输入局部身份证号" class="account"></el-input><br>
            学工号：<el-input v-model="user_no" placeholder="请输入局部学工号" class="account"></el-input>
            性别：<el-select v-model="user_sex" placeholder="请选择性别">
						<el-option
						v-for="item in sex_options"
						:key="item.value"
						:label="item.label"
						:value="item.value">
						</el-option>
					</el-select>
            账号状态：<el-select v-model="user_status" placeholder="请选择账号状态">
						<el-option
						v-for="item in status_options"
						:key="item.value"
						:label="item.label"
						:value="item.value">
						</el-option>
					</el-select>
            <el-button @click="clearItem">清除条件</el-button>
            <el-button type="primary" @click="queryAllUserInfo">查询</el-button>
          <br>
          <el-button type="primary" size="mini" @click="importDialogChange">批量导入师生信息</el-button>
          <hr>
    <el-table :data="tableData" style="width: 100%"> <!--height="250"-->
        <el-table-column fixed prop="type_is" label="身份" style="width: 10%"></el-table-column>
        <el-table-column prop="user_no" label="学工号" style="width: 10%"></el-table-column>
        <el-table-column prop="user_name" label="姓名" style="width: 10%"></el-table-column>
        <el-table-column prop="user_sex" label="性别" style="width: 10%"></el-table-column>
        <el-table-column prop="id_card" label="身份证号" style="width: 10%"></el-table-column>
        <el-table-column prop="dept" label="所属部门" style="width: 10%"></el-table-column>
        <el-table-column prop="user_status" label="账号状态" style="width: 10%"></el-table-column>
        <el-table-column label="操作" fixed="right" style="width: 20%">
            <template slot-scope="scope">
                <el-button @click="delThisUser(scope.row,scope.$index,tableData)" type="text" size="small">直接删除该用户<br>(无询问提示)</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-col :span="24" class="xtes">
        <el-col :span="24" >
        <div class="xtesbox">
        <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="pageSize"
                    class
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                >
                </el-pagination></div>
        </el-col>
    </el-col>

<el-dialog
  title="通过表格批量导入师生信息"
  :visible.sync="dialogVisibleForImport"
  width="30%">
          <h5>下载导入模板</h5>
          <el-button type="primary" @click="download">点击下载"师生信息导入模板"</el-button>
          <hr>
          <h5>选择表格文件</h5>
          <span>（选择文件后，请点击确认进行解析导入）</span>
          <form id="tf0" enctype="multipart/form-data">
            <table>
              <tr>
                <th></th>
                <th><input type="file" name="upfile" style="border: solid 1px black"/></th>
              </tr>
            </table>
          </form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleForImport = false">取 消</el-button>
    <el-button type="primary" @click="upload">确 认</el-button>
  </span>
</el-dialog>

        </div>
      </div>
      <!-- /Page Wrapper -->
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import BreadCrumb from '@/components/Breadcrumb'
import Header from '@/components/Header'
import SideBar from '@/components/SideBar'
export default {
  created(){
    this.queryAllUserInfo()
  },
  beforeDestroy(){
  },
  mounted(){
  },
  data(){
      return {
        currentPage: 1,
		    pageSize: 10,
		    total: 0,
        tableData:[],
        // 查询个人信息条件
        user_type: '',
        type_options: [
            {
                label: '学生',
                value: 'Student'
            },
            {
                label: '职工',
                value: 'Teacher'
            },
        ],
        user_no: '',
        user_name: '',
        id_card: '',
        user_sex: '',
        sex_options: [
            {
                label: '男',
                value: '男'
            },
            {
                label: '女',
                value: '女'
            },
            {
                label: '未填写',
                value: '未填写'
            }
        ],
        user_status: '',
        status_options: [
            {
                label: '未激活',
                value: '未激活'
            },
            {
                label: '已激活',
                value: '已激活'
            },
            {
                label: '失效',
                value: '失效'
            }
        ],
        // excel导入信息弹窗
        dialogVisibleForImport: false,
      }
  },
  methods: {
    upload(){
      var form = document.getElementById('tf0')
      let formd = new FormData(form);
      /*
        已经在main.js处理，一旦post请求带有header["Content-Type": "multipart/form-data"]那就不会强转其格式为JSON

        文件上传的一个禁区，关于formdata：formdata无法在axios下使用get方式发送请求，只能使用post。
        如果非不得已想要使用get,那就试一试ajax，我也不确定ajax是否可以，但是Postman工具Get/Post的Formdata都是支持的。
      */
      let config = {
          method: 'post',  // main.js拦截器保持get请求原生格式，不会强转成json
          url: 'edu/admin/infoImport',
          data: formd,
          headers: {
            "Content-Type": "multipart/form-data"
          }
      };
      this.$http((config))
      .then((response)=>{
        if(response.data.statusCode === 1){
          this.$message.success(response.data.msg);
        }else{
          this.$message({
              message: response.data.msg,
              type: 'error',
              //type 取值 success(成功) /warning(警告)/info(消息)/error(错误)/;
          });
        }
      }).catch(error => {
          this.$message.error("failed, please try again later.");
          console.log(error)
      });

    }, // end upload()
    download() {
				let config = {
					method: 'get',
					url: 'edu/common/infoTemplate',
					responseType: 'blob'
				};
				this.$http(config)
					.then((response) => {
						// 提取文件名
						const filename = decodeURI(response.headers["content-disposition"].split("fileName=")[1])
						console.log(filename)
						// 将二进制流转为blob
						const blob = new Blob([response.data], {
							type: 'application/octet-stream'
						})
						if (typeof window.navigator.msSaveBlob !== 'undefined') {
							// 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
							window.navigator.msSaveBlob(blob, filename)
						} else {
							// 创建新的URL并指向File对象或者Blob对象的地址
							const blobURL = window.URL.createObjectURL(blob)
							// 创建a标签，用于跳转至下载链接
							const tempLink = document.createElement('a')
							tempLink.style.display = 'none'
							tempLink.href = blobURL
							tempLink.setAttribute('download', filename)
							// 兼容：某些浏览器不支持HTML5的download属性
							if (typeof tempLink.download === 'undefined') {
								tempLink.setAttribute('target', '_blank')
							}
							// 挂载a标签
							document.body.appendChild(tempLink)
							tempLink.click()
							document.body.removeChild(tempLink)
							// 释放blob URL地址
							window.URL.revokeObjectURL(blobURL)
						}
					}).catch(error => {
						this.$message.error("下载失败，请重试或者联系管理员");
						console.log(error)
					});
			}, // download() End
      // 师生信息查询和删除部分
      // 查询全体师生信息
      queryAllUserInfo(){
        this.tableData=[]
        this.total=0
        let config = {
            method: 'post',
            url: 'edu/teabase/user_info',
            headers: {
                "Content-Type": "application/json;"
            },
            data: {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                user_type: this.user_type,
                user_no: this.user_no,
                name: this.user_name,
                id_card: this.id_card,
                user_sex: this.user_sex,
                user_status: this.user_status
            }
        };
        this.$http(config)
        .then((response)=>{
            if (response.data.statusCode == 1){
                this.tableData=response.data.page.list
                this.total=response.data.page.totalCount
            }else{
                this.$message.warning(response.data.msg);
            }
        }).catch(error => {
            this.$message.error("query failed, please try again later.");
            console.log(error)
        });
      },
    handleSizeChange(val) {
        this.pageSize = val;
        this.queryAllUserInfo();
        console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
        this.currentPage = val;
        this.queryAllUserInfo();
        console.log(`当前页: ${val}`);
    },
    handleSelectionChange(data) {
        console.log('获取row', data)
        // 当前多选的数据
        this.multipleSelection = data;
    },
        clearItem(){
            this.user_type = '',
            this.user_no = ''
            this.user_name = ''
            this.id_card = ''
            this.user_sex = ''
            this.user_status = ''
        },
    importDialogChange(){
      this.dialogVisibleForImport = true
    },
    delThisUser(row, index,tabledata){
        let config = {
            method: 'delete',
            url: 'edu/admin/user_manage',
            headers: {
                "Content-Type": "application/json;"
            },
            data:JSON.stringify({
                userId: row.id_is,
                userType: row.type_is
            })
        };
        this.$http(config)
        .then((response)=>{
            if (response.data.statusCode == 1){
                this.$message.success(response.data.msg);
                this.queryAllUserInfo()
            }else{
                this.$message.warning(response.data.msg);
            }
        }).catch(error => {
            this.$message.error("query failed, please try again later.");
            console.log(error)
        });
    },
  },
  components: {
	Header,
    BreadCrumb,
	  SideBar
  }
}
</script>

<style>
.account{
    width: 200px;
    height: 35px;
    margin-bottom: 20px;
    padding-left: 10px;
}
.xtes {
    margin-top: 20px;
    margin-bottom: 20px;
}
.xtesbox{
    float: right;
    padding-right: 150px;
}
</style>